/*
 * Copyright (c) gitee.com/jiandong001.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import hilog from '@ohos.hilog';
import HashMap from '@ohos.util.HashMap';
import Context from '@ohos.application.context';

import { Assertions } from '../inner/Assertions';
import { SurfaceDelegateFactory } from '../common/SurfaceDelegateFactory';
import { ReactContext } from '../bridge/ReactContext';
import { DevBundleDownloadListener } from './DevBundleDownloadListener';
import { RequestHandler } from '../packagerConnection/RequestHandler';
import { ReactInstanceDevHelper } from './ReactInstanceDevHelper';
import { DevSupportManagerBase } from './DevSupportManagerBase';

export class BridgeDevSupportManager extends DevSupportManagerBase {
  private mIsSamplingProfilerEnabled: boolean = false;
  private static readonly TAG1: string = "React BridgeDevSupportManager"
  //context
  public constructor(abilityContext: Context.AbilityContext, reactInstanceManagerHelper: ReactInstanceDevHelper,
                     packagerPathForJSBundleName: string, enableOnCreate: boolean,
                     /*redBoxHandler?: RedBoxHandler, */
                     devBundleDownloadListener: DevBundleDownloadListener,
                     minNumShakes: number, customPackagerCommandHandlers: HashMap<string, RequestHandler>,
                     surfaceDelegateFactory: SurfaceDelegateFactory) {
    super(abilityContext, reactInstanceManagerHelper, packagerPathForJSBundleName, enableOnCreate, /*redBoxHandler,*/
      devBundleDownloadListener, minNumShakes, customPackagerCommandHandlers, surfaceDelegateFactory);
    //  if (this.getDevSettings().isStartSamplingProfilerOnInit()) {
    //  if (!this.mIsSamplingProfilerEnabled) {
    //  this.toggleJSSamplingProfiler();
    //} else {
    //  Toast.makeText(applicationContext, "JS Sampling Profiler was already running, so did not start the sampling profiler", 1).show();
    //}

    hilog.info(0x0000, BridgeDevSupportManager.TAG1, 'constructor');

  }

  //this.addCustomDevOption(this.mIsSamplingProfilerEnabled ? "Disable Sampling Profiler" : "Enable Sampling Profiler", new DevOptionHandler() {
  //            public void onOptionSelected() {
  //                BridgeDevSupportManager.this.toggleJSSamplingProfiler();
  //            }
  //});
  //if (!this.getDevSettings().isDeviceDebugEnabled()) {
  //            this.addCustomDevOption(this.getDevSettings().isRemoteJSDebugEnabled() ? applicationContext.getString(string.catalyst_debug_stop) : applicationContext.getString(string.catalyst_debug), new DevOptionHandler() {
  //                public void onOptionSelected() {
  //                    BridgeDevSupportManager.this.getDevSettings().setRemoteJSDebugEnabled(!BridgeDevSupportManager.this.getDevSettings().isRemoteJSDebugEnabled());
  //                    BridgeDevSupportManager.this.handleReloadJS();
  //                }
  //            });
  //        }
  //
  //}

  public handleReloadJS(): void {
    //  UiThreadUtil.assertOnUiThread();
    //  ReactMarker.logMarker(ReactMarkerConstants.RELOAD, this.getDevSettings().getPackagerConnectionSettings().getDebugServerHost());
    //  this.hideRedboxDialog();
    if (this.getDevSettings().isRemoteJSDebugEnabled()) {
      //    PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Proxy");
      //    this.showDevLoadingViewForRemoteJSEnabled();
      //    this.reloadJSInProxyMode();
    } else {
      //            PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: load from Server");
      Assertions.assertNotNull(this.getJSAppBundleName() != null)
      let bundleURL: string = this.getDevServerHelper().getDevServerBundleURL(this.getJSAppBundleName());
      this.reloadJSFromServer(bundleURL);
    }

  }

  //public loadSplitBundleFromServer(bundlePath: string, callback: DevSplitBundleCallback): void {
  //        this.fetchSplitBundleAndCreateBundleLoader(bundlePath, new CallbackWithBundleLoader() {
  //            public void onSuccess(JSBundleLoader bundleLoader) {
  //                bundleLoader.loadScript(BridgeDevSupportManager.this.getCurrentContext().getCatalystInstance());
  //                ((HMRClient)BridgeDevSupportManager.this.getCurrentContext().getJSModule(HMRClient.class)).registerBundle(BridgeDevSupportManager.this.getDevServerHelper().getDevServerSplitBundleURL(bundlePath));
  //                callback.onSuccess();
  //            }
  //
  //            public void onError(String url, Throwable cause) {
  //                callback.onError(url, cause);
  //            }
  //        });
  //    }

  //private JSExecutorConnectCallback getExecutorConnectCallback(final SimpleSettableFuture<Boolean> future) {
  //        return new JSExecutorConnectCallback() {
  //            public void onSuccess() {
  //                future.set(true);
  //                BridgeDevSupportManager.this.hideDevLoadingView();
  //            }
  //
  //            public void onFailure(Throwable cause) {
  //                BridgeDevSupportManager.this.hideDevLoadingView();
  //                FLog.e("ReactNative", "Failed to connect to debugger!", cause);
  //                future.setException(new IOException(BridgeDevSupportManager.this.getApplicationContext().getString(string.catalyst_debug_error), cause));
  //            }
  //};
  //}

  //private reloadJSInProxyMode(): void {
  //        this.getDevServerHelper().launchJSDevtools();
  //        Factory factory = new Factory() {
  //            public JavaJSExecutor create() throws Exception {
  //                WebsocketJavaScriptExecutor executor = new WebsocketJavaScriptExecutor();
  //                SimpleSettableFuture<Boolean> future = new SimpleSettableFuture();
  //                executor.connect(BridgeDevSupportManager.this.getDevServerHelper().getWebsocketProxyURL(), BridgeDevSupportManager.this.getExecutorConnectCallback(future));
  //
  //                try {
  //                    future.get(90L, TimeUnit.SECONDS);
  //                    return executor;
  //                } catch (ExecutionException var4) {
  //                    throw (Exception)var4.getCause();
  //                } catch (TimeoutException | InterruptedException var5) {
  //  throw new RuntimeException(var5);
  //}
  //}
  //};
  //this.getReactInstanceDevHelper().onReloadWithJSDebugger(factory);
  //}

  protected getUniqueTag(): string {
    return "Bridge";
  }

  //private void toggleJSSamplingProfiler() {
  //        JavaScriptExecutorFactory javaScriptExecutorFactory = this.getReactInstanceDevHelper().getJavaScriptExecutorFactory();
  //        if (!this.mIsSamplingProfilerEnabled) {
  //            try {
  //                javaScriptExecutorFactory.startSamplingProfiler();
  //                Toast.makeText(this.getApplicationContext(), "Starting Sampling Profiler", 0).show();
  //            } catch (UnsupportedOperationException var18) {
  //  Toast.makeText(this.getApplicationContext(), javaScriptExecutorFactory.toString() + " does not support Sampling Profiler", 1).show();
  //} finally {
  //  this.mIsSamplingProfilerEnabled = true;
  //}
  //} else {
  //            try {
  //                String outputPath = File.createTempFile("sampling-profiler-trace", ".cpuprofile", this.getApplicationContext().getCacheDir()).getPath();
  //                javaScriptExecutorFactory.stopSamplingProfiler(outputPath);
  //                Toast.makeText(this.getApplicationContext(), "Saved results from Profiler to " + outputPath, 1).show();
  //            } catch (IOException var15) {
  //                FLog.e("ReactNative", "Could not create temporary file for saving results from Sampling Profiler");
  //            } catch (UnsupportedOperationException var16) {
  //  Toast.makeText(this.getApplicationContext(), javaScriptExecutorFactory.toString() + "does not support Sampling Profiler", 1).show();
  //} finally {
  //  this.mIsSamplingProfilerEnabled = false;
  //}
  //}
  //
  //}
}
